package com.rybbaby.tss.platform.initializer;

import com.rybbaby.tss.core.initializer.AbstractAutomaticInit;
import com.rybbaby.tss.core.utils.SpringApplicationContextUtil;
import com.rybbaby.tss.platform.sysDictionary.entity.SysDictionary;
import com.rybbaby.tss.platform.sysDictionary.service.ISysDictionaryService;
import com.rybbaby.tss.platform.sysDictionaryGroup.entity.SysDictionaryGroup;
import com.rybbaby.tss.platform.sysDictionaryGroup.service.ISysDictionaryGroupService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description 数据字典初始化器
 * 
 * @author 谢进伟
 * 
 * @createDate 2017年12月30日 上午9:32:31
 */
public class SysDictionaryInitializer extends AbstractAutomaticInit {
	
	/** 所有字典分组 **/
	private static List<SysDictionaryGroup> allGroup;
	/** 所有字典配置 **/
	private static List<SysDictionary> allDictionaryList;
	/** 以分编码为key的映射 **/
	private static Map<String , List<SysDictionary>> groupMap = new HashMap<String , List<SysDictionary>>();
	
	@Override
	public void autoInit() {
		load();
	}
	
	/**
	 * 初始化所有未被禁用的字典分组及分组项
	 */
	public static void load() {
		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		cachedThreadPool.execute(new Runnable() {
			
			@Override
			public void run() {
				allDictionaryList = SpringApplicationContextUtil.getContext().getBean(ISysDictionaryService.class).findByProperty("isForbidden" , false);// 未被禁用
				allGroup = SpringApplicationContextUtil.getContext().getBean(ISysDictionaryGroupService.class).findByProperty("isForbidden" , false);// 未被禁用
				if(allGroup != null && !allGroup.isEmpty()) {
					groupMap.clear();
					for(SysDictionaryGroup group : allGroup) {
						for(SysDictionary sysDictionary : allDictionaryList) {
							if(sysDictionary.getGroupId().equals(group.getId())) {
								String key = group.getCode();// 分组编码
								if(groupMap.containsKey(key)) {
									groupMap.get(key).add(sysDictionary);
								} else {
									List<SysDictionary> list = new ArrayList<SysDictionary>();
									list.add(sysDictionary);
									groupMap.put(key , list);
								}
							}
						}
					}
				}
			}
		});
		cachedThreadPool.shutdown();
	}
	
	/**
	 * @return 以分组码为key的映射
	 */
	public static Map<String , List<SysDictionary>> getGroupMap() {
		return groupMap;
	}
	
	/**
	 * @return 获取所有系统参数配置信息
	 */
	public static List<SysDictionary> getAllDictionaryList() {
		return allDictionaryList;
	}
	
	/**
	 * 获取指定分组下的所有字典项
	 * 
	 * @param groupCode
	 *            分组编码
	 * @return
	 */
	public static List<SysDictionary> geDictionaryByGroupName(String groupCode) {
		return groupMap.get(groupCode);
	}
}
